package action;

import java.lang.reflect.ParameterizedType;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import tools.LogUtil;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public abstract class baseAction<T> extends ActionSupport implements ModelDriven<T> ,SessionAware{

	protected T model;

	private String page;
	private String rows;
	private Map<String, Object> map;
	private Map session;

	// 首页
	public abstract String index();

	// 异步获取列表数据
	public abstract String getJsonList();
	
	//根据id删除
	public abstract String deleteById();
	
	//保存
	public abstract String save();
	
	//查询
	public abstract String find();
	
	//更新
	public abstract String update();
	
	//检查用户是否登录
	public boolean checkUserLogin(){
		Object object = getRequest().getSession().getAttribute("user");
		return (object == null) ? false:true;
	}

	//获取已经登录的用户名
	public String getLoginAccount(){
		return (String)getSession().get("user");
	}
	
	@Override
	public T getModel() {
		return model;
	}

	public void setModel(T model) {
		this.model = model;
	}

	public Class getService() {
		return this.getClass();
	}

	public baseAction() {
		try {
			ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
			Class<T> clazz = (Class<T>) type.getActualTypeArguments()[0];
			model = (T) clazz.newInstance();
		} catch (Exception e) {
			LogUtil.out("反射获取类出现异常");
			throw new RuntimeException(e);
		}
	}

	public int getStartPage(){
		 int pageNumber = Integer.parseInt((page == null || page == "0") ? "1": page);
		 return (pageNumber-1)*getPageSize();
	}
	
	public int getPageSize(){
		return Integer.parseInt((rows == null || rows == "0") ? "10" : rows);
	}
	
	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public Map<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}

	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	public Map getSession() {
		return session;
	}

	public void setSession(Map session) {
		this.session = session;
	}
	

}
